package com.cjp.run;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.cjp.utils.FileUtils;

/**
 * Hello world!
 *
 */
@SpringBootApplication
public class Application
{
	private static Map<String,String> tokenMap=new HashMap<String, String>();
	private static Map<String,Date> dateMap=new HashMap<String, Date>();
	
	public static String getToken(){
		Date date=dateMap.get(FileUtils.currentAppidThread.get());
		if(date!=null){
			Date currDate=new Date();
			if(currDate.getTime()-date.getTime()>1000*60*100){//获取token
				try {
					getToken_getTicket();
					dateMap.put(FileUtils.currentAppidThread.get(),new Date());
				} catch (Exception e) {
					e.printStackTrace();
					for(int i=0;i<3;i++){
						try {
							getToken_getTicket();
							dateMap.put(FileUtils.currentAppidThread.get(),new Date());
							break;
						} catch (Exception e1) {
							e1.printStackTrace();
							try {
								Thread.sleep(10000);
							} catch (InterruptedException e2) {
								e2.printStackTrace();
							}
						}
					}
				}
			}else{
				return tokenMap.get(FileUtils.currentAppidThread.get());
			}
		}else{
			try {
				getToken_getTicket();
				dateMap.put(FileUtils.currentAppidThread.get(),new Date());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return tokenMap.get(FileUtils.currentAppidThread.get());
	}
	
	public static String isValid() throws Exception{
		Date date=dateMap.get(FileUtils.currentAppidThread.get());
		if(date!=null){
			Date currDate=new Date();
			if(currDate.getTime()-date.getTime()>1000*60*100){//获取token
				getToken_getTicket();
				dateMap.put(FileUtils.currentAppidThread.get(),new Date());
			}else{
				return tokenMap.get(FileUtils.currentAppidThread.get());
			}
		}else{
			getToken_getTicket();
			dateMap.put(FileUtils.currentAppidThread.get(),new Date());
		}
		return tokenMap.get(FileUtils.currentAppidThread.get());
	}
	
	
    public static void main( String[] args )
    {
        SpringApplication.run(Application.class, args);
    	/*FileUtils.currentAppidThread.set("wx7bcef4e8b3cacf01");
    	FileUtils.currentAppAppsecretThread.set("f0939e56bdc3bdba8a716239c52671da");
    	try {
			getToken_getTicket();
		} catch (Exception e) {
			e.printStackTrace();
		}*/
    }
    
    /**
     * @method sendWechatmsgToUser
     * @描述: TODO(发送模板信息给用户) 
     * @参数@param touser  用户的openid
     * @参数@param templat_id  信息模板id
     * @参数@param url  用户点击详情时跳转的url
     * @参数@param topcolor  模板字体的颜色
     * @参数@param data  模板详情变量 Json格式
     * @参数@return
     * @返回类型：String
     * @添加时间 2016-1-5上午10:38:45
     * @作者：***
     */
    public static String sendWechatmsgToUser(String touser, String templat_id, String clickurl, String topcolor, JSONObject data){
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        String token = getToken();//JsapiTicketTimeTask.access_token;  //微信凭证，access_token
        if(token==null){
        	token = getToken();
        }
        String url = tmpurl.replace("ACCESS_TOKEN", token);
        JSONObject json = new JSONObject();
        try {
            json.put("touser", touser);
            json.put("template_id", templat_id);
            json.put("url", clickurl);
            json.put("topcolor", topcolor);
            json.put("data", data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("templat_id:"+templat_id+";openid:"+touser+";appid:"+FileUtils.currentAppidThread.get());
        String result = httpsRequest(url, "POST", json.toString());
        try {
            JSONObject resultJson = JSONObject.parseObject(result);
            String errmsg = (String) resultJson.get("errmsg");
            if(!"ok".equals(errmsg)){  //如果为errmsg为ok，则代表发送成功，公众号推送信息给用户了。
                return "error";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "success";
    }
    
    public static String getUserList(){
    	String url="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+ getToken()+"&next_openid=";
    	String result = httpsRequest(url, "GET", null);
    	System.out.println(result);
    	return result;
    }
    
    
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr){
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时：{}");
        } catch (Exception e) {
            System.out.println("https请求异常：{}");
        }
        return null;
    }
    
    
    /**
     * @Description: 任务执行体
     * @param @throws Exception
     * @date 2016年3月10日 下午2:04:37
     */
    public static void getToken_getTicket() throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        params.put("grant_type", "client_credential");
        params.put("appid", FileUtils.currentAppidThread.get());
        params.put("secret", FileUtils.currentAppAppsecretThread.get());
        String jstoken = httpsRequest(buildUrl("https://api.weixin.qq.com/cgi-bin/token",params),"GET", null);
        System.out.println(jstoken);
        String access_token = JSONObject.parseObject(jstoken).getString(
                "access_token"); // 获取到token并赋值保存
        tokenMap.put(FileUtils.currentAppidThread.get(), access_token);
    }
    /**
     * 构建get方式的url
     * 
     * @param reqUrl
     *            基础的url地址
     * @param params
     *            查询参数
     * @return 构建好的url
     */
    public static String buildUrl(String reqUrl, Map<String, String> params) {
        StringBuilder query = new StringBuilder();
        Set<String> set = params.keySet();
        for (String key : set) {
            query.append(String.format("%s=%s&", key, params.get(key)));
        }
        return reqUrl + "?" + query.toString();
    }
    
    
     
}
